package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private FileStorageService fileStorageService;
    @Value("${file.oss.prefix}")
    String prefix;
    @Value("${file.oss.web-site}")
    String webSite;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    /**
     * 上传素材
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //校验参数
            //判断文件是否有效
        if(multipartFile==null&&multipartFile.getSize()<=0){
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"文件不能为空");
        }
            //判断文件格式
                //获取文件名称
        String filename = multipartFile.getOriginalFilename();
        //截取后缀名
        String suffix = filename.substring(filename.lastIndexOf("."));
        if (!checkSuffix(suffix)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文件格式不符合要求");
        }
        //判断是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"需要登录后才能操作");
        }
        //将文件上传到oss
        String fileName =null;
        try {
            //使用UUID产生新的id
            String newFileName= UUID.randomUUID().toString().replaceAll("-","")+suffix;
            fileName = fileStorageService.store(prefix, newFileName, multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"文件上传失败");
        }
        //创建素材对象，设置文件路径
        WmMaterial material = new WmMaterial();
        material.setUserId(user.getId());
        material.setUrl(fileName);
        material.setType((short)0);
        material.setIsCollection((short)0);
        material.setCreatedTime(new Date());
        this.save(material);
        //将素材对象回显给前端
        material.setUrl(webSite+material.getUrl());
        return ResponseResult.okResult(material);
    }

    /**
     * 查询素材列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findById(WmMaterialDTO dto) {
        //校验参数
        dto.checkParam();
        //分页查询
        Page<WmMaterial> wmMaterialPage = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery();
        //判断是否为收藏素材
        if(dto.getIsCollection()!=null && dto.getIsCollection()==1){
             wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        // 校验用户是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"需要登录后操作");
        }
        //按照userID查询当前登录用户上传的素材
        wrapper.eq(WmMaterial::getUserId,user.getId());
        //按照时间降序排列
        wrapper.orderByDesc(WmMaterial::getCreatedTime);

        IPage<WmMaterial> page = page(wmMaterialPage, wrapper);
        List<WmMaterial> records = page.getRecords();
        //将回显的图片路径加上前缀
        for (WmMaterial record : records) {
            record.setUrl(webSite+record.getUrl());
        }
        //封装结果
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
        return responseResult;
    }

    /**
     * 根据id删除素材
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteById(Integer id) {
        //1.校验参数 id 登录
        if(id==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"id不能为空");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"需要登录后才操作");
        }
        // 2.业务处理
        // 判断当前id是否被引用，如果被使用则禁止删除
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<WmNewsMaterial> wrapper = Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id);
        //根据id查询出来的个数
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        //判断个数是否大于0
        if(count>0){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"数据已经被引用，不允许删除操作");
        }
        //删除中间表数据
        removeById(id);
        //删除图片
        fileStorageService.delete(wmMaterial.getUrl());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏与取消收藏
     * @param id
     * @return
     */
    @Override
    public ResponseResult updateById(Integer id, Short type) {
        //校验参数
        //校验id
        if(id==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"id为空");
        }
        //校验登录
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"需要登录后才能操作");
        }
        //更新状态
        WmMaterial wmMaterial = getById(id);
        //判断用户是否有素材信息
        if(wmMaterial==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"素材信息不存在");
        }
        //获取当前用户信息
        if(!wmMaterial.getUserId().equals(user.getId())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"只允许收藏自己的素材信息");
        }
        //修改收藏数据
        wmMaterial.setIsCollection(type);
        updateById(wmMaterial);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 检查后缀格式是否满足
     * @return
     */
    public boolean checkSuffix(String suffix){
        if(StringUtils.isBlank(suffix)){
            return false;
        }
        boolean isCheck = false;
        List<String> allowSuffix = Arrays.asList(".jpg",".jpeg",".png",".gif");
        for (String s : allowSuffix) {
            if( s.equalsIgnoreCase(suffix)){
                isCheck =true;
                break;
            }
        }
        return isCheck;
    }
}
